
package com.sbtr.business.calibration.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.open.calibration.dto.CalibrationDetailsDto;
import com.sbtr.open.calibration.dto.CalibrationTxtEntityMapDto;
import com.sbtr.business.calibration.entity.*;
import com.sbtr.business.calibration.mapper.CalibrationTxtEntityMapMapper;
import com.sbtr.business.calibration.service.ICalibrationTxtEntityMapService;
import com.sbtr.constant.CalibrationConstant;
import com.sbtr.constant.ColumnConstant;
import com.sbtr.util.BeanCopyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;


/**
 * <p>
 * 标定集 服务实现类
 * </p>
 *

 */
@Transactional
@Service
public class CalibrationTxtEntityMapServiceImpl extends ServiceImpl<CalibrationTxtEntityMapMapper, CalibrationTxtEntityMap>
		implements ICalibrationTxtEntityMapService {

    private static final Logger logger = LoggerFactory.getLogger(CalibrationTxtEntityMapServiceImpl.class);
    @Autowired
    private CalibrationServiceImpl calibrationService;
    @Autowired
    private CalibrationDetailsServiceImpl calibrationDetailsService;
    @Autowired
    private CalibrationTxtEntityServiceImpl calibrationTxtEntityService;
    @Autowired
    private CalibrationRecordDailyServiceImpl calibrationRecordDailyService;

    @Override
    public CalibrationTxtEntityMapDto saveTxtEntityLabels(@PathVariable("id") Long calibrationDetailsId,
                                                          @RequestBody CalibrationTxtEntityMapDto dto){
        //保存打标签记录
        CalibrationTxtEntityMap data = BeanCopyUtils.copyProperties(dto, CalibrationTxtEntityMap.class);
        data.setCreateTime(new Date());
        boolean tag = saveOrUpdate(data);

        if (tag) {
            //更新文本calibrationTxtEntity状态（已完成)和实体标签信息（更新json）
            updateCalibrationTxtEntity(dto.getTxtId());
            // 更新发布任务的数据统计
            CalibrationDetailsDto calibrationDetailsDto = calibrationDetailsService.findById(calibrationDetailsId);
            updateCalibrationImgCount(calibrationDetailsDto.getCalibrationId());
            //更新个人接受任务的数据统计
//            CalibrationDto calibrationDto=calibrationService.findById(calibrationId);
            updateCalibrationDetailsImgCount(calibrationDetailsDto);
            //更新每日标注统计
            updateCalibrationTxtEntityRecordDaily(calibrationDetailsDto);
        }

        return BeanCopyUtils.copyProperties(data, CalibrationTxtEntityMapDto.class);
    }

    @Override
    public List<CalibrationTxtEntityMapDto> batchSaveTxtEntityLabels(@PathVariable("id") Long calibrationDetailsId,
                                                                     @RequestBody List<CalibrationTxtEntityMapDto> dtos){
        //保存打标签记录
        List<CalibrationTxtEntityMap> dataList = BeanCopyUtils.copyProperties(dtos, CalibrationTxtEntityMap.class);
        for (CalibrationTxtEntityMap data : dataList) {
            data.setCreateTime(new Date());
        }
        boolean tag = saveOrUpdateBatch(dataList);

        if (tag) {
            //更新文本calibrationTxtEntity状态（已完成)和实体标签信息（更新json）
            updateCalibrationTxtEntity(dtos.get(0).getTxtId());
            // 更新发布任务的数据统计
            CalibrationDetailsDto calibrationDetailsDto = calibrationDetailsService.findById(calibrationDetailsId);
            updateCalibrationImgCount(calibrationDetailsDto.getCalibrationId());
            //更新个人接受任务的数据统计
//            CalibrationDto calibrationDto=calibrationService.findById(calibrationId);
            updateCalibrationDetailsImgCount(calibrationDetailsDto);
            //更新每日标注统计
            updateCalibrationTxtEntityRecordDaily(calibrationDetailsDto);
        }

        return BeanCopyUtils.copyProperties(dataList, CalibrationTxtEntityMapDto.class);
    }

    //更新calibrationTxtEntity状态--->已完成,同时更新文本的所有的实体标签信息（更新json）
    @Override
    public boolean updateCalibrationTxtEntity(Long txtId){
        //获取json
        QueryWrapper<CalibrationTxtEntityMap> queryWrapper = new QueryWrapper<CalibrationTxtEntityMap>();
        queryWrapper.eq("txt_id", txtId);
        List<CalibrationTxtEntityMap> dataList = list(queryWrapper);
//        JSONObject json = new JSONObject();
        //[{'entity': '广州', 'label': '城市'},{'entity': '时代地产', 'label': '房地产名'}]
        JSONArray jsonArr = new JSONArray();
        dataList.stream().forEach(item -> {
            //   txt_json{'entity': '广州', 'label': '城市'}
            JSONObject jo = new JSONObject();
            jo.put("entity", item.getEntity());
            jo.put("label", item.getClassifyName());
            jsonArr.add(jo);
        });
//        json.put("result",jsonArr);

        CalibrationTxtEntity cte = calibrationTxtEntityService.getById(txtId);
        cte.setCompleted("1");//已完成
        cte.setTxtJson(jsonArr.toString());
        return calibrationTxtEntityService.updateById(cte);
    }

    // 更新文本实体类型的发布任务的数据统计
    @Override
    public boolean updateCalibrationImgCount(Long calibrationId) {
        Calibration calibration = calibrationService.getById(calibrationId);
        if (null != calibration){
            QueryWrapper<CalibrationTxtEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("calibration_id", calibrationId);
            Integer totalCount = calibrationTxtEntityService.count(wrapper);
            wrapper.eq("completed", "1");
            Integer completeCount = calibrationTxtEntityService.count(wrapper);

            calibration.setTotalCount(totalCount);
            calibration.setCompleted(completeCount);
            if(completeCount.equals(totalCount)){
                calibration.setStatus(CalibrationConstant.TASK_STATUS_COMPLETED);
            }

            return calibrationService.updateById(calibration);
        }
        return false;
    }

    // 更新文本实体类型的个人接受任务的数据统计
    @Override
    public boolean updateCalibrationDetailsImgCount(CalibrationDetailsDto calibrationDetailsDto) {

        QueryWrapper<CalibrationTxtEntity> wrapper = new QueryWrapper<>();
        Long calibrationIds = calibrationDetailsDto.getCalibrationId();
        String finisher = calibrationDetailsDto.getFinisher();
        wrapper.eq("calibration_id", calibrationIds);
        wrapper.eq("finisher",finisher);
        Integer totalCount = calibrationTxtEntityService.count(wrapper);
        wrapper.eq("completed", "1");
        Integer completeCount = calibrationTxtEntityService.count(wrapper);

        CalibrationDetails calibrationDetails = BeanCopyUtils.copyProperties(calibrationDetailsDto, CalibrationDetails.class);
        calibrationDetails.setTotalCount(totalCount);
        calibrationDetails.setCompleted(completeCount);
        if(completeCount.equals(totalCount)){
            calibrationDetails.setStatus(CalibrationConstant.TASK_STATUS_COMPLETED);
        }

        return calibrationDetailsService.updateById(calibrationDetails);
    }

    @Override
    public boolean updateCalibrationTxtEntityRecordDaily(CalibrationDetailsDto calibrationDetails){
        QueryWrapper<CalibrationTxtEntity> wrapper = new QueryWrapper<>();
        long calibrationId = calibrationDetails.getCalibrationId();
        String finisher = calibrationDetails.getFinisher();
        wrapper.eq("calibration_id", calibrationId);
        wrapper.eq("finisher",finisher);
//		Integer totalCount = count(wrapper);
        wrapper.eq("completed", "1");
        Calendar calendar = new GregorianCalendar();
        //        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(new Date());//当天时间赋给日历对象
        calendar.set(Calendar.HOUR_OF_DAY, 0);//设置对象日历格式
        calendar.set(Calendar.MINUTE, 0);//设置为当天零点
        calendar.set(Calendar.SECOND, 0);
        Date updateTimeFrom = calendar.getTime();//再返回时间对象
        calendar.add(Calendar.DAY_OF_MONTH, 1);//把日期往后增加一天,整数  往后推,负数往前移动
        Date updateTimeTo = calendar.getTime();//返回另一个时间对象
        wrapper.between(ColumnConstant.UPDATE_TIME, updateTimeFrom, updateTimeTo);
        Integer completeCount = calibrationTxtEntityService.count(wrapper);
        CalibrationRecordDaily calibrationRecordDaily = calibrationRecordDailyService.findByCalibrationIdFinisher(calibrationId, finisher);
        if(null == calibrationRecordDaily){
            calibrationRecordDaily = new CalibrationRecordDaily();
            calibrationRecordDaily.setCalibrationId(calibrationId);
            calibrationRecordDaily.setFinisher(finisher);
            calibrationRecordDaily.setCalibrationDetailId(calibrationDetails.getId());
            calibrationRecordDaily.setUpdateTime(new Date());
            calibrationRecordDaily.setCompletedCount(completeCount);
        }else {
            calibrationRecordDaily.setUpdateTime(new Date());
            calibrationRecordDaily.setCompletedCount(completeCount);
        }
        return calibrationRecordDailyService.saveOrUpdate(calibrationRecordDaily);
    }


    @Override
    public List<CalibrationTxtEntityMapDto> loadOneTxtEntityLabels(@RequestParam("txtId")Long txtId){
        QueryWrapper<CalibrationTxtEntityMap> queryWrapper = new QueryWrapper<CalibrationTxtEntityMap>();
        queryWrapper.eq("txt_id",txtId);
        List<CalibrationTxtEntityMap> items = this.list(queryWrapper);
        return BeanCopyUtils.copyProperties(items,CalibrationTxtEntityMapDto.class);
    }



}